package mvc.controller;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.UUID;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import bean.entity.Message;
import bean.transfer.MessageJoinUser;
import jakarta.servlet.http.HttpSession;
import service.MessageService;
import spring.SpringContextUtil;

@Controller
@RequestMapping("/message")
public class MessageController{
  @GetMapping
  public String load(Model model, HttpSession seesion){
    String username = (String) seesion.getAttribute("name");
    if(username != null) {
      model.addAttribute("username", seesion.getAttribute("name"));
      model.addAttribute("actionname", "退出");
      model.addAttribute("actionurl", "'./logout'");
    }else {
      model.addAttribute("username", "游客");
      model.addAttribute("actionname", "登录");
      model.addAttribute("actionurl", "'./login'");
    }
    return "message"; // 视图message.jsp
  }
  
  @ResponseBody
  @PostMapping("/get")
  public List<MessageJoinUser> list(@RequestBody Map<String, String> data){
    MessageService ms = (MessageService) SpringContextUtil.getBean("messageService");
    return ms.getMessages(20, Integer.valueOf(data.get("page")));
  }
  
  @ResponseBody
  @PostMapping("/add")
  public Map<String, Boolean> add(@RequestBody Map<String, String> data, HttpSession session){
    MessageService ms = (MessageService) SpringContextUtil.getBean("messageService");
    Map<String, Boolean> res = new HashMap<String, Boolean>();
    String uid = (String) session.getAttribute("uid");
    if(uid != null) {
      String msgid = UUID.randomUUID().toString();
      String content = data.get("content");
      Timestamp time = new Timestamp(System.currentTimeMillis());
      res.put("posted", ms.post(new Message(msgid, uid, content, time)));
    }
    return res;
  }
}
